package com.neulogistics.contrib.procuredcenter.api.application.query;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.neulogistics.contrib.procuredcenter.api.application.converter.VendorPOVMConverter;
import com.neulogistics.contrib.procuredcenter.api.application.converter.VendorQueryPOConverter;
import com.neulogistics.contrib.procuredcenter.api.application.viewmodel.VendorViewModel;
import com.neulogistics.contrib.procuredcenter.domain.model.valueobject.VendorInfo;
import com.neulogistics.contrib.procuredcenter.infrastructure.persistence.orm.po.GoodsPO;
import com.neulogistics.contrib.procuredcenter.infrastructure.persistence.orm.po.VendorPO;
import com.neulogistics.contrib.procuredcenter.infrastructure.persistence.orm.service.IGoodsPOService;
import com.neulogistics.contrib.procuredcenter.infrastructure.persistence.orm.service.IVendorPOService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class VendorQueryService implements IVendorQueryService {
    @Resource
    IVendorPOService vendorPOService;

    @Resource
    IGoodsPOService goodsPOService;

    @Override
    public VendorViewModel getById(Integer vendorId) {
        VendorPO vendorPO = vendorPOService.getById(vendorId);

        VendorViewModel vendorViewModel = VendorPOVMConverter.POToVM(vendorPO);

        return vendorViewModel;
    }

    @Override
    public VendorViewModel getByGoodsId(Integer goodsId) {
        GoodsPO goodsPO = goodsPOService.getById(goodsId);
        VendorInfo vendorInfo = JSONUtil.toBean(goodsPO.getVendorInfo(), VendorInfo.class);
        VendorPO vendorPO = vendorPOService.getById(vendorInfo.getVendorId());
        VendorViewModel vendorViewModel = VendorPOVMConverter.POToVM(vendorPO);
        return vendorViewModel;
    }

    @Override
    public Page<VendorViewModel> page(VendorQuery vendorQuery) {
        // 取出条件
        VendorPO vendorPOQuery = VendorQueryPOConverter.queryToPO(vendorQuery);
        long current = vendorQuery.getPageNum();
        long pageSize = vendorQuery.getPageSize();

        // 查询
        QueryWrapper<VendorPO> queryWrapper = new QueryWrapper<>(vendorPOQuery);
        Page<VendorPO> page = vendorPOService.page(new Page<>(current, pageSize), queryWrapper);

        // 构造结果
        Page<VendorViewModel> viewModelPage = new Page<>(current, pageSize);
        List<VendorViewModel> viewModelList = page.getRecords().stream()
                .map(VendorPOVMConverter::POToVM).collect(Collectors.toList());
        viewModelPage.setRecords(viewModelList);
        viewModelPage.setTotal(page.getTotal());

        return viewModelPage;
    }
}
